from math import sqrt

class Vector3D:
    """ a stripped out class for 3D vectors"""
    
    def __mul__(self,s):
        """Returns a Vector3D result of multiplication by scalar s"""
        return Vector3D([self.__V[i]*s for i in range(3)])
    
    def __add__(self,A):
        return Vector3D(tuple([A[i]+self.__V[i] for i in range(3)])) 
        
    def __init__(self, V=(0,0,0)):
        self.__V=V
        

    def asTuple(self):
        return self.__V

    def __getitem__(self,i):
        return self.__V[i]
        
    def dotProduct(self, b):
        """simple dot product function"""
        return sum([self.__V[i]*b[i] for i in range(3)])
    
    def len(self):
        return sqrt(sum([self.__V[i]*self.__V[i] for i in range(3)]))
    
    def normalize(self):
        fLength =  self.len()
        if fLength > 1e-08 :
            fInvLength = 1.0 / fLength;
            self.__V=self.__V*fInvLength
            return fLength
        return 0
    
    def crossProduct(self,V):
        
        return Vector3D(tuple(self.__V[1] * V[2] - self.__V[2] * V[1],\
                        self.__V[2] * V[0] - self.__V[0] * V[2],\
                        self.__V[0] * V[1] - self.__V[1] * V[0]))
       


class LocalSpace:
    """          ----------------------------------------------------------------------------


     OpenSteer -- Steering Behaviors for Autonomous Characters

     Copyright (c) 2002-2003, Sony Computer Entertainment America
     Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>

     Permission is hereby granted, free of charge, to any person obtaining a
     copy of this software and associated documentation files (the "Software"),
     to deal in the Software without restriction, including without limitation
     the rights to use, copy, modify, merge, publish, distribute, sublicense,
     and/or sell copies of the Software, and to permit persons to whom the
     Software is furnished to do so, subject to the following conditions:

     The above copyright notice and this permission notice shall be included in
     all copies or substantial portions of the Software.

     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
     THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
     FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
     DEALINGS IN THE SOFTWARE.


     ----------------------------------------------------------------------------


     LocalSpace: a local coordinate system for 3d space

     Provide functionality such as transforming from local space to global
     space and vice versa.  Also regenerates a valid space from a perturbed
     "forward vector" which is the basis of abnstract vehicle turning.

     These are comparable to a 4x4 homogeneous transformation matrix where the
     3x3 (R) portion is constrained to be a pure rotation (no shear or scale).
     The rows of the 3x3 R matrix are the basis vectors of the space.  They are
     all constrained to be mutually perpendicular and of unit length.  The top
     ("x") row is called "side", the middle ("y") row is called "up" and the
     bottom ("z") row is called forward.  The translation vector is called
     "position".  Finally the "homogeneous column" is always [0 0 0 1].
d
         [ R R R  0 ]      [ Sx Sy Sz  0 ]
         [ R R R  0 ]      [ Ux Uy Uz  0 ]
         [ R R R  0 ]  ->  [ Fx Fy Fz  0 ]
         [          ]      [             ]
         [ T T T  1 ]      [ Tx Ty Tz  1 ]

     This file defines three classes:
       AbstractLocalSpace:  pure virtual interface
       LocalSpaceMixin:     mixin to layer LocalSpace functionality on any base
       LocalSpace:          a concrete object (can be instantiated)

    """
    
    ZERO=Vector3D((0,0,0))
    UNIT_X=Vector3D((1,0,0))
    UNIT_Y=Vector3D((0,1,0))
    UNIT_Z=Vector3D((0,0,1))
    
    def side(self):
        return self.__side
    
    def up(self):
        return self.__up
    
    def forward(self):
        return self.__forward
    
    def position(self):
        return self.__position
        
    def setSide(self,s):
        if not (s is Vector3D) : s=Vector3D(s)
        
        self.__side=s
        return s
        
    def setUp(self,u):
        if not (u is Vector3D) : u=Vector3D(u)
        self.__up=u
        return u
    def setForward(self, f):
        if not (f is Vector3D) : f=Vector3D(f)
        self.__forward=f
        return f
    
    def setPosition(self, p):
        if not (p is Vector3D) : p=Vector3D(p)
        self.__position=p
        return p
    
        
    def rightHanded(self):
        "use right-(or left-)handed coordinate space"
        return True
    
    def resetLocalSpace(self):
        """ ------------------------------------------------------------------------
         reset transform: set local space to its identity state, equivalent to a
         4x4 homogeneous transform like this:
        
             [ X 0 0 0 ]
             [ 0 1 0 0 ]
             [ 0 0 1 0 ]
             [ 0 0 0 1 ]
        
         where X is 1 for a left-handed system and -1 for a right-handed system."""
        self.__forward=Vector3D((0,0,1))
        self.__side=self.localRotateForwardToSide (self.__forward)
        self.__up=Vector3D((0,1,0))
        self.__position = Vector3D((0, 0, 0))
    
       
    
    
    def localizeDirection(self, globalDirection):
        """transform a direction in global space to its equivalent in local space"""
        if not (globalDirection is Vector3D) : globalDirection=Vector3D(globalDirection)
        
        return Vector3D((globalDirection.dotProduct(self.__side),\
                globalDirection.dotProduct(self.__up),\
                globalDirection.dotProduct(self.__forward)))
     
    def globalizePosition(self, localPosition):
        """transform a point in local space to its equivalent in global space"""
        return self.__position+globalizeDirection (localPosition)

    def globalizeDirection(self, localDirection):
        """transform a direction in local space to its equivalent in global space"""
        return self.__side*localDirection[0]+ self.__up*localDirection[1]+ self.__forward*localDirection[2]
                                
    def setUnitSideFromForwardAndUp(self):
        """set "side" basis vector to normalized cross product of forward and up"""
        if rightHanded():
            #_side.cross (_forward, _up);
            self.__side = self.__forward.crossProduct(self.__up);
        else:
            #_side.cross(_up, _forward);
            self.__side = self.__up.crossProduct(self.__forward);

        self.__side.normalise ();
    
    def regenerateOrthonormalBasisUF(self, newUnitForward):
        """ regenerate the orthonormal basis vectors given a new forward
           (which is expected to have unit length)"""
        
        if not (newUnitForward is Vector3D) : newUnitForward=Vector3D(newUnitForward)
                
        self.__forward = newUnitForward;

        # derive new side basis vector from NEW forward and OLD up
        setUnitSideFromForwardAndUp ();

        # derive new Up basis vector from new Side and new Forward
        # (should have unit length since Side and Forward are
        # perpendicular and unit length)
        if rightHanded():
            
            self.__up=self.__side.crossProduct( self.__forward);
        else:
            #_up.cross (_forward, _side);
            self.__up = self.__forward.crossProduct(self.__side);

    def regenerateOrthonormalBasis(self, newForward):
        """for when the new forward is NOT know to have unit length"""
        
        if not (newForward is Vector3D) : newForward=Vector3D(newForward)
        
        newForward.normalise()
        regenerateOrthonormalBasisUF (newForward)    

    
    def regenerateOrthonormalBasisWithUp(self, newForward,newUp):
        """ for supplying both a new forward and and new up"""
        
        if not (newForward is Vector3D) : newForward=Vector3D(newForward)
        if not (newUp is Vector3D) : newUp=Vector3D(newUp)
        
        self.__up = newUp
        newForward.normalise()
        regenerateOrthonormalBasis(newForward)    
        
    def localRotateForwardToSide (self, v):
        """rotate, in the canonical direction, a vector pointing in the
        "forward" (+Z) direction to the "side" (+/-X) direction"""
        
        if not rightHanded() : v[2]=-v[2]
        return Vector3D((v[2],v[1],v[0]))
    

class AbstractVehicle(LocalSpace) :
    
        
    
    def mass(self):
        """mass (defaults to unity so acceleration=force)"""
        return 0
    
    def setMass(self,mass):
        return 0

    # size of bounding sphere, for obstacle avoidance, etc.
    def radius(self):
        """size of bounding sphere, for obstacle avoidance, etc."""
        return 0
    
    def setRadius(self,radius):
        return 0

    # velocity of vehicle
    def velocity(self): return Vector3D.ZERO

    # speed of vehicle  (may be faster than taking magnitude of velocity)
    def speed(self) : return 0
    
    def setSpeed(self,speed) : return 0

    
    def predictFuturePosition(self, predictionTime) : 
        """ groups of (pointers to) abstract vehicles, and iterators over them
        #typedef std::vector<AbstractVehicle*> group;
        #typedef group::const_iterator iterator;    

        # predict position of this vehicle at some time in the future
        # (assumes velocity remains constant)"""
        return Vector3D.ZERO
    
    

    
    def maxForce(self):
        """the maximum steering force this vehicle can apply"""
        return 0
    
    def setMaxForce(self,max): return 0
    

    
    def maxSpeed(self):
        """the maximum speed this vehicle is allowed to move"""
        return 0
    
    def setMaxSpeed(self, max): return 0
    
        
    
